import './Css/Left.css';
import React, { useState, useEffect } from 'react';
import { Fields, Tables, DropTable, DuplicateTable, TruncateTable, RenameTable } from '../wailsjs/go/main/App';
import { IconApps, IconUnlink } from '@douyinfe/semi-icons';
import { Tree, Select, Button, Spin, Toast } from '@douyinfe/semi-ui';
import { ContextMenuTrigger, ContextMenu, ContextMenuItem } from 'rctx-contextmenu';
import { IconTable, IconSideSheet, IconForm, IconSkeleton, IconToken } from '@douyinfe/semi-icons-lab';
import { w2prompt, w2utils } from 'w2ui/w2ui-2.0.es6';

function Left(props) {
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [treeData, setTreeData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [reloadTableTime, setReloadTableTime] = useState(1);  // 用于刷新使用

    useEffect(() => {
        if (props.table) Fields(props.database, props.table).then(items => props.updateFields(items))
    }, [props.table])

    useEffect(() => {
        // setTreeData([])
        // setExpandedKeys([])

        // 如果没有选择数据库则情况已经选择表
        if (!props.database?.length) {
            props.updateTable('')
            return;
        }
        setLoading(true)

        // 获取表
        Tables(props.database).then((items) => {
            const tables = []
            const views = []
            items['tables']?.map((item) => tables.push({ label: item, value: item, key: item, icon: (<IconApps style={{ color: '#997d1f' }} />), children: [] }))
            items['views']?.map((item) => views.push({ label: item, value: item, key: item, icon: (<IconApps style={{ color: '#997d1f' }} />), children: [] }))

            const newTreeData = [
                { label: 'Tables', value: 'tables', key: 'tables', icon: (<IconTable />), children: tables },
                { label: 'Views', value: 'views', key: 'views', icon: (<IconSideSheet />), children: views },
                {
                    label: 'Functions',
                    value: 'functions',
                    key: 'functions',
                    icon: (<IconSkeleton />),
                    children: [
                        {
                            label: 'f_batch_create_jobs',
                            value: 'f_batch_create_jobs',
                            key: 'f_batch_create_jobs',
                            icon: (<IconApps style={{ color: 'var(--semi-color-text-2)' }} />),
                            children: [],
                        }
                    ]
                },
                {
                    label: 'Queries',
                    value: 'queries',
                    key: 'queries',
                    icon: (<IconForm />),
                    children: [
                        {
                            label: 'select jobs',
                            value: 'queries-0',
                            key: 'queries-0',
                            icon: (<IconApps style={{ color: 'var(--semi-color-text-2)' }} />),
                            children: [],
                        }
                    ]
                }
            ];
            setTreeData(newTreeData)
            setExpandedKeys(['tables'])
            setLoading(false)
        }).catch((e) => {
            Toast.error(e);
            setLoading(false);
        });
    }, [props.database, reloadTableTime]);

    return (
        <Spin spinning={loading}>
            <div style={{ paddingLeft: 10 }}>
                <Select placeholder="Select DB" style={{ marginTop: 25, marginLeft: 10, width: 230, display: props.connect.connect_type === 'sqlite' ? 'none' : '' }}
                    value={props.database}
                    onChange={value => props.updateDatabase(value)}
                    size='default'
                    prefix={<IconToken />}
                    showArrow={false}
                    showClear={true}>
                    {props.databases.map((item, _) => (
                        <Select.Option value={item}>{item}</Select.Option>
                    ))}
                </Select>
                <div style={{ height: 'calc(1000px - 100px)', overflowX: 'hidden', overflowY: 'auto' }}>
                    <Tree
                        style={{ width: 250 }}
                        treeData={treeData}
                        filterTreeNode={true}
                        searchPlaceholder={'Filter'}
                        showFilteredOnly={true}
                        labelEllipsis={true}
                        emptyContent={'No Data'}
                        directory={true}
                        expandedKeys={expandedKeys}
                        onExpand={expandedKeys => {
                            setExpandedKeys(expandedKeys);
                        }}
                        onChange={(value) => {
                            if (!['tables', 'queries', 'views', 'functions'].includes(value)) props.updateTable(value)
                        }}
                        onSearch={(inputValue, filteredExpandedKeys) => {
                            setExpandedKeys([...filteredExpandedKeys]);
                        }}
                        renderLabel={(label, data) => {
                            return <>
                                <ContextMenuTrigger
                                    id={"table-" + label}
                                >
                                    <div style={{ display: 'flex', alignItems: 'center' }}> {label} </div>
                                </ContextMenuTrigger>

                                <ContextMenu
                                    hideOnLeave={true}
                                    id={"table-" + label}
                                    animation={'fade'}
                                >
                                    <ContextMenuItem onClick={() => { }}>View Data</ContextMenuItem>
                                    <ContextMenuItem onClick={(event) => event.preventDefault()}>View Struct</ContextMenuItem>
                                    <ContextMenuItem onClick={() => {
                                        w2prompt({
                                            label: 'New name',
                                            value: label
                                        }).ok(event => {
                                            const newName = event.detail.value.trim();
                                            if (!newName || newName.includes(' ')) {
                                                w2utils.notify('Please enter a valid table name', { error: true })
                                                return;
                                            }
                                            RenameTable(props.database, label, newName).then((result) => {
                                                if (result) {
                                                    w2utils.notify(e, { error: true })
                                                } else {
                                                    Toast.success('Rename table ' + label + ' to ' + newName + ' successfully')
                                                    setReloadTableTime(reloadTableTime + 1)
                                                }
                                            }).catch(e => w2utils.notify(e, { error: true }))
                                        })
                                    }}>Rename</ContextMenuItem>
                                    <ContextMenuItem onClick={() => { }}>Copy Name</ContextMenuItem>
                                    <ContextMenuItem onClick={() => {
                                        DropTable(props.database, label).then((result) => {
                                            if (result) {
                                                w2utils.notify(e, { error: true })
                                            } else {
                                                Toast.success('Drop table ' + label + ' successfully')
                                                setReloadTableTime(reloadTableTime + 1)
                                            }
                                        }).catch(e => w2utils.notify(e, { error: true }))
                                    }}>Drop</ContextMenuItem>
                                    <ContextMenuItem onClick={() => {
                                        TruncateTable(props.database, label).then((result) => {
                                            if (result) w2utils.notify(e, { error: true })
                                            else {
                                                Toast.success('Truncate table ' + label + ' successfully')
                                                setReloadTableTime(reloadTableTime + 1)
                                            }
                                        }).catch(e => w2utils.notify(e, { error: true }))
                                    }}>Truncate</ContextMenuItem>
                                    <ContextMenuItem onClick={() => {
                                        w2prompt({
                                            label: 'New table',
                                            value: label + '_copy'
                                        }).ok(event => {
                                            const newName = event.detail.value.trim();
                                            if (!newName || newName.includes(' ')) {
                                                w2utils.notify('Please enter a valid table name', { error: true })
                                                return;
                                            }
                                            DuplicateTable(props.database, label, event.detail.value).then((result) => {
                                                if (result) w2utils.notify(e, { error: true })
                                                else {
                                                    Toast.success('Duplicate table ' + label + ' successfully')
                                                    setReloadTableTime(reloadTableTime + 1)
                                                }
                                            }).catch(e => w2utils.notify(e, { error: true }))
                                        })
                                    }}>Duplicate</ContextMenuItem>
                                    <ContextMenuItem onClick={() => { }}>New Table</ContextMenuItem>
                                </ContextMenu>

                            </>;
                        }}
                    />
                </div>
                <Button onClick={() => props.updateConnect(null)}><IconUnlink /></Button>
            </div>
        </Spin>
    );
};

export default Left;
